import { fromError } from 'zod-validation-error'
import { createCaseSchema, casesTable } from '~~/server/db/schema/case'
import { db } from '~~/server/db'

export default defineEventHandler(async (event) => {
  const validationResult = await readValidatedBody(event, (body) =>
    createCaseSchema.safeParse(body)
  )
  if (!validationResult.success) {
    throw createError({
      statusCode: 400,
      message: fromError(validationResult.error).toString()
    })
  }
  try {
    const {
      orderId,
      orderType,
      batch,
      clientName,
      plaintiff,
      overduePrincipal,
      name,
      idCard,
      phone,
      address,
      lender,
      legalAssistant,
      mediator,
      guarantor,
      litigationTeam,
      court,
      caseStatus
    } = validationResult.data
    // 创建用户
    const [newCase] = await db
      .insert(casesTable)
      .values({
        court,
        orderId,
        orderType,
        batch,
        clientName,
        plaintiff,
        overduePrincipal,
        name,
        idCard,
        phone,
        address,
        lender,
        legalAssistant,
        mediator,
        guarantor,
        litigationTeam,
        caseStatus
      })
      .$returningId()
    setResponseStatus(event, 201)
    return {
      message: '案件创建成功',
      data: newCase.id
    }
  } catch (error: any) {
    throw createError({
      statusCode: 500,
      message: '创建案件失败'
    })
  }
})
